package com.nbcio.modules.flowable.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.nbcio.modules.flowable.apithird.entity.SysUser;
import com.nbcio.modules.flowable.apithird.service.IFlowThirdService;

import lombok.AllArgsConstructor;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.delegate.DelegateExecution;
import org.jeecg.common.util.SpringContextUtils;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 多实例collect用户处理类
 *
 * @author nbacheng
 * @date 2022-10-16
 */
@AllArgsConstructor
@Component("multiInstanceHandler")
public class MultiInstanceHandler {

    public HashSet<String> getUserName(DelegateExecution execution) {
        HashSet<String> candidateUserName = new LinkedHashSet<>();
        FlowElement flowElement = execution.getCurrentFlowElement();
        if (ObjectUtil.isNotEmpty(flowElement) && flowElement instanceof UserTask) {
            UserTask userTask = (UserTask) flowElement;
            if (CollUtil.isNotEmpty(userTask.getCandidateUsers())) {
            	candidateUserName.addAll(userTask.getCandidateUsers());
            } else if (CollUtil.isNotEmpty(userTask.getCandidateGroups())) {
            	List<String> groups = userTask.getCandidateGroups();
                IFlowThirdService iFlowThirdService = SpringContextUtils.getBean(IFlowThirdService.class);
                groups.forEach(item -> {
                     List<SysUser> listuserName = iFlowThirdService.getUsersByRoleId(item);
                     for(SysUser sysuser : listuserName) {
                        candidateUserName.add(sysuser.getUsername());
                     }
                });
            }
        }
        return candidateUserName;
    }
}
